#include <sr04.h>
#include <lcd.h>
#include <REGX52.H>

sbit TRIG_port = P2 ^ 3;
sbit ECHO_port = P2 ^ 4;

bit UltraWave_Flag = 0;
float time;
int dis;
int num1 = 0, num2, num3, num4;

void Delay10us()
{
	unsigned char i;
	i = 2;
	while (--i);
}

void InitTimer0(void)
{
	TMOD = 0x11; // T1-mode1   T0-mode1
	// initialize T0
	TH0 = 0;
	TL0 = 0;
	// initialize T1
	TH1 = (0xff + 1 - 2000) / 256;
	TL1 = (0xff + 1 - 2000) % 256;
	IE = 0x8a; // 1000 1010
	// start T1
	TR1 = 1;
}

void distance()
{
	while (!ECHO_port);
	TR0 = 1;
	while (ECHO_port);
	TR0 = 0;
	time = TH0 * 256 + TL0;
	dis = time * 0.017;
	TH0 = 0;
	TL0 = 0;
}

void show_sr04(void)
{
	string(0x80, "DIS:");

	distance();
	write_data(0x30 + dis / 10);
	write_data(0x30 + dis % 10);
}

void timer0_interrupt() interrupt 1
{
	UltraWave_Flag = 1;
}

void timer1_interrupt() interrupt 3
{
	static int c = 0;
	// initialize T1
	TH1 = (0xff + 1 - 2000) / 256;
	TL1 = (0xff + 1 - 2000) % 256;
	if (++c >= 100)
	{ /// 100 X 2ms
		c = 0;
		TRIG_port = 1;
		delay(1);
		TRIG_port = 0;
	}
}
